<?php


namespace App\Services\Member\Services;

use App\Constant\ApiV2Constant;
use App\Services\Member\Interfaces\ActivityServiceInterface;
use App\Services\Member\Models\Activity;
use Illuminate\Support\Facades\DB;

class ActivityService implements ActivityServiceInterface
{






    public function createActivity(int $userId, int $activityId, string $type): void
    {

        $activity = Activity::query()->where('activityable_id',$activityId)->where('activityable_type', ucfirst($type))->first();
        if ($activity) {
            $activity->update(['user_id' => $userId,  'activityable_id' => $activityId, 'activityable_type' => $type]);
        }else{
            Activity::create(['user_id' => $userId, 'activityable_id' => $activityId, 'activityable_type' => $type]);
        }


    }



    public function getActivities(array $userIds, int $page, int $size)
    {

        $query = Activity::query()->whereIn('user_id', $userIds)->orderBy('created_at', 'desc');
        $total = $query->count();
        $activities = $query->orderBy('activityable_type')->forPage($page, $size)->get();

        $groups = $activities->groupBy('activityable_type')->map(function ($group) {
                $resourceIds = $group->pluck('activityable_id')->implode(',');
                return [
                    'activityable_type' => $group->first()->activityable_type,
                    'resource_ids' => $resourceIds,
                ];
            })
            ->values();
        $records = [];
// 遍历每个分组，根据 resource_id 查询对应的记录，并按照创建时间排序
        foreach ($groups as $key => $group) {
            // 获取分组中的 resource_id，转换为数组形式
            $ids = explode(',', $group['resource_ids']);
            $resource = new $group['activityable_type']();
            $type =substr($group['activityable_type'], strrpos($group['activityable_type'], '\\') + 1);
            // 查询对应的记录
            $records[] = $resource::query()
                ->with(ApiV2Constant::MODEL_ACTIVITY_WITH_FIELD[$type])
                ->select(ApiV2Constant::MODEL_ACTIVITY_FIELD[$type])
                ->addSelect(DB::raw("'{$type}' AS type"))
                ->whereIn('id', $ids)
                ->orderBy('created_at', 'desc')
                ->get()
                ->toArray();

        }
        $list = [];
        foreach ($records as $item) {
            $list = array_merge($list, $item);
        }

// 对所有的记录按照创建时间排序
        usort($list, function ($a, $b) {
            return strtotime($b['created_at']) - strtotime($a['created_at']);
        });

        return compact('list', 'total');
    }


//


}
